package com.tecode.myBooks.shoppingCart.dao;

import com.tecode.myBooks.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-12-10
 * @Description:
 */
public class ShoppingDao {

	public int addCart(String productId, int nums, int userId) {
		int rows =0;

		Connection conn = null;
		PreparedStatement ps = null;
		try {
				conn =DBUtil.getConnection();
				String sql ="insert into shoppingcart (userid,productid,nums,addProductCreate) values(?,?,?,now())";

				ps = conn.prepareStatement(sql);

				ps.setInt(1,userId);
				ps.setString(2,productId);
				ps.setInt(3,nums);


			rows = ps.executeUpdate();

		}catch (Exception e){
			e.printStackTrace();
		}finally {
			DBUtil.close(conn,ps,null);
		}



		return  rows;
	}

	public boolean getShoppCartByUserIdAndproductId(String productId, int userId) {

		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn =DBUtil.getConnection();
			String sql ="select id from  shoppingcart where userid = ? and productid = ?";

			ps = conn.prepareStatement(sql);

			ps.setInt(1,userId);
			ps.setString(2,productId);

			if(ps.executeQuery().next()){
				return true;
			}

		}catch (Exception e){
			e.printStackTrace();
		}finally {
			DBUtil.close(conn,ps,null);
		}

		return false;
	}

	public int updateShoppCartByUserIdAndproductId(String productId, int nums, int userId) {

		int rows =0;

		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn =DBUtil.getConnection();
			String sql ="update shoppingcart set nums = nums +? where userid =? and productId = ?";

			ps = conn.prepareStatement(sql);

			ps.setInt(1,nums);
			ps.setString(3,productId);
			ps.setInt(2,userId);


			rows = ps.executeUpdate();

		}catch (Exception e){
			e.printStackTrace();
		}finally {
			DBUtil.close(conn,ps,null);
		}



		return  rows;

	}
}